var config = require('./server/config')
var _  = require('lodash')
var path = require('path')
var webpack = require('webpack')
var glob = require('glob')
var ExtractTextPlugin = require('extract-text-webpack-plugin'); //css单独打包

var ROOT_PATH = path.resolve(__dirname)
var APP_PATH = path.resolve(ROOT_PATH, 'app')

// 获取指定路径下的入口文件
function getEntries(globPath) {
  var files = glob.sync(globPath),
    entries = {};

  files.forEach(function(filepath) {
    // 取倒数第二层(view下面的文件夹)做包名
    var split = filepath.split('/');
    var name = split[split.length - 2];

    entries[name] = filepath;
  });

  return entries;
}

function getEntryAndPlugin() {
  var entries = getEntries(APP_PATH + '/pages/**/index.jsx');
  var entrys = {}
  entrys["vendor"] = [// 把第三方的依赖打成一个包js包
    'babel-polyfill',
    'react',
    'react-dom',
    'react-router',
    'react-redux',
    'redux',
    'redux-thunk',
    'lodash',
    'isomorphic-fetch',
    'immutable',
    'shortid',
  ]

  var plugins = []
  plugins.push(new webpack.IgnorePlugin(/\.svg$/))
  plugins.push(new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(config.env)
    }
  }))
  // 根据entrys里面的vendors列表,提取公共部分打成vendors.js文件
  plugins.push(new webpack.optimize.CommonsChunkPlugin('vendors', 'js/vendors.js'))
  plugins.push(new webpack.HotModuleReplacementPlugin())
  plugins.push(new ExtractTextPlugin('[name].css'))

  let dev_server = `webpack-dev-server/client?http://${config.dev_hot_server_host}:${config.dev_hot_server_port}`
  let dev_hot_server = 'webpack/hot/dev-server'

  _.map(entries, (filepath, name) => {
    name = name.toLowerCase();
    // 每个页面生成一个entry
    entrys[name] = []
    entrys[name].push(dev_server)
    entrys[name].push(dev_hot_server)
    entrys[name].push(filepath)
  })

  return { entrys, plugins }
}

var obj = getEntryAndPlugin()

var webpackConfig = {
  entry: obj.entrys,
  output: {// output.publicPath 表示资源的发布地址，当配置过该属性后，打包文件中所有通过相对路径引用的资源都会被配置的路径所替换。
    path: __dirname + '/public/static/',
    filename: 'js/[name].js',
    publicPath: '/static/'
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.less', '.scss', '.css'], //后缀名自动补全
    root: APP_PATH
  },
  module: {
    //preLoaders: [
    //  {
    //    test: /\.jsx?$/,
    //    loaders: ['eslint'],
    //    include: APP_PATH
    //  }
    //],
    loaders: [
      {
        test: /\.jsx?$/,
        // loaders: ['react-hot', 'babel?' + JSON.stringify({presets: ['react', 'es2015', 'stage-0']})],
        loaders: ['react-hot', 'babel'],
        include: APP_PATH,
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract('style', ['css', 'autoprefixer']),
        include: [APP_PATH]
      },
      {
        test: /\.less$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract('style', ['css', 'autoprefixer', 'less']),
        include: [APP_PATH]
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract('style', ['css', 'autoprefixer', 'sass']),
        include: [APP_PATH]
      },
      {
        test: /\.(png|jpg|ico)$/,
        loader: 'url-loader?limit=8192&name=images/[name].[ext]'
      }
    ]
  },
  jshint: {
    "esnext": true
  },
  plugins: obj.plugins
}

module.exports = webpackConfig
